<template>
  <div class="customTimer" :class="{'isBorder':isBorder}">
    <div v-if="isTitle" class="timer-title">{{ title }}</div>
    <div v-if="isInterval" class="timer-box" :class="{'isBorder':isBorder,smallFont:type==='datetime'}">
      <van-field v-model="startTime" label="" placeholder="开始时间" class="startTime" input-align="center" clickable readonly @click="openTimerPicker('interval')" />
      <span>至</span>
      <van-field v-model="endTime" label="" placeholder="结束时间" class="endTime" input-align="center" clickable readonly @click="openTimerPicker('interval')" />
    </div>
    <div v-if="!isInterval" class="timer-box" :class="{'isBorder':isBorder}">
      <van-field v-model="dateTime" label="" :placeholder="'请选择' + title" input-align="left" clickable readonly @click="openTimerPicker('once')" />
      <i v-if="isShowIcon" class="iconfont down">&#xe656;</i>
    </div>
    <!-- 单独时间 -->
    <van-popup v-model="showTimer" position="bottom" get-container="body">
      <van-datetime-picker ref="datetimePicker" v-model="timeValue" :max-date="maxDate" :min-date="minDate" :type="getTimerType" :formatter="formatter" :class="{'isYear':type==='year'}" @cancel="showTimer = false" @confirm="onConfirm" />
      <!-- <van-button v-if="isClear" type="warning" class="w-100" @click="clearTimer">清空</van-button> -->
    </van-popup>
    <!-- 时间区间 -->
    <van-calendar
      ref="intervalCalendar"
      v-model="showCalendar"
      type="range"
      :allow-same-day="true"
      :round="false"
      get-container=".aaaa"
      :min-date="minDate"
      :max-date="maxDate"
      :default-date="calendarValue"
      :show-confirm="false"
      color="#409EFF"
      @confirm="onConfirm"
    >
      <template #footer>
        <div class="py-1">
          <van-button v-if="isClear" type="warning" class="w-100" @click="clearTimer">清空</van-button>
        </div>
      </template>
    </van-calendar>
  </div>
</template>

<script>
import { getQuickTimer, parseTime } from '@/utils'
import { currentTime } from '@/utils/dayJs'

export default {
  props: {
    // 时间类型 可选值为 year(年) date(年-月-日) year-month(年-月) month-day(月-日) datehour(年-月-日-时) datetime(年-月-日-时-分)
    type: {
      type: String,
      default: 'date'
    },
    // 是否显示icon
    isShowIcon: {
      type: Boolean,
      default: true
    },
    // 开始时间
    start: {
      type: String,
      default: ''
    },
    // 结束时间
    end: {
      type: String,
      default: ''
    },
    // 是否需要边框
    isBorder: {
      type: Boolean,
      default: true
    },
    // 是否需要边框
    isClear: {
      type: Boolean,
      default: true
    },
    // 是否需要title
    isTitle: {
      type: Boolean,
      default: true
    },
    // 是否是时间区间
    isInterval: {
      type: Boolean,
      default: true
    },
    // 时间值
    dateValue: {
      type: String,
      default: ''
    },
    // 标题
    title: {
      type: String,
      default: '报警时间'
    },
    // 选择时间标题
    pickerTitle: {
      type: String,
      default: ''
    },
    /**
     * 可选择时间的范围
     * 1. 不加限制
     * 2. 不可选中未来时间
     * 3. 不可选中过去时间
     * */
    timeRange: {
      type: [Number, String],
      default: 2
    }
  },
  data() {
    return {
      startTime: '',
      endTime: '',
      dateTime: '',
      showTimer: false,
      showCalendar: false,
      timeValue: '',
      typePicker: 'start',
      calendarValue: [],
      timeInterval: 10
      // minDate: new Date(2023, 0, 1)
    }
  },
  computed: {
    dateFormatter() {
      let formatter = ''
      switch (this.type) {
        case 'date':
          formatter = '{y}-{m}-{d}'
          break
        case 'year':
          formatter = '{y}'
          break
        case 'year-month':
          formatter = '{y}-{m}'
          break
        case 'month-day':
          formatter = '{m}-{d}'
          break
        case 'datehour':
          formatter = '{y}-{m}-{d} {h}'
          break
        case 'datetime':
          formatter = '{y}-{m}-{d} {h}:{m}'
          break
      }
      return formatter
    },
    getTimerType() {
      return this.type === 'year' ? 'year-month' : this.type
    },
    maxDate() {
      const timeRange = Number(this.timeRange)
      const date = new Date()
      let maxDate = new Date()
      if (timeRange === 1) {
        maxDate = new Date(Number(currentTime('年')) + this.timeInterval + '-12-31')
      } else if (timeRange === 2) {
        maxDate = date
      } else if (timeRange === 3) {
        maxDate = new Date(Number(currentTime('年')) + this.timeInterval + '-12-31')
      }
      return maxDate
    },
    minDate() {
      const timeRange = Number(this.timeRange)
      const date = new Date()
      let minDate = new Date()
      if (timeRange === 1) {
        minDate = new Date(Number(currentTime('年')) - this.timeInterval + '-01-01')
      } else if (timeRange === 2) {
        minDate = new Date(Number(currentTime('年')) - this.timeInterval + '-01-01')
      } else if (timeRange === 3) {
        minDate = date
      }
      return minDate
    }
  },
  watch: {
    start(nv) {
      this.startTime = nv
    },
    end(nv) {
      this.endTime = nv
    },
    dateValue(nv) {
      this.dateTime = nv
    }
  },
  mounted() {
    if (this.isInterval) {
      this.startTime = this.start
      this.endTime = this.end
    } else {
      this.dateTime = this.dateValue
    }

    if (this.type === 'year') {
      this.timeInterval = 100
    } else {
      this.timeInterval = 20
    }
  },
  methods: {
    openTimerPicker(type) {
      this.typePicker = type
      if (type === 'interval') {
        if (this.startTime !== '' && this.endTime !== '') {
          this.calendarValue = [
            new Date(...this.setTimer(this.startTime)),
            new Date(...this.setTimer(this.endTime))
          ]
        } else {
          this.calendarValue = [
            new Date(...this.setTimer(parseTime(getQuickTimer('近一天').start, '{y}-{m}-{d}'))),
            new Date(...this.setTimer(parseTime(getQuickTimer('近一天').end, '{y}-{m}-{d}')))
          ]
        }
        this.showCalendar = true
      } else {
        this.dateValue !== '' ? (this.timeValue = new Date(...this.setTimer(this.dateValue)))
          : (this.timeValue = new Date())
        if (this.type === 'year') {
          this.timeValue = this.dateValue ? new Date(this.dateValue) : new Date()
        }
        this.showTimer = true
      }
    },
    formatter(type, val) {
      if (type === 'year') {
        return val + '年'
      }
      if (type === 'month') {
        return val + '月'
      }
      if (type === 'day') {
        return val + '日'
      }
      if (type === 'hour') {
        return val + '时'
      }
      if (type === 'minute') {
        return val + '分'
      }
      return val
    },
    onConfirm(value) {
      if (this.typePicker === 'interval') {
        this.startTime = parseTime(value[0], this.dateFormatter)
        this.endTime = parseTime(value[1], this.dateFormatter)
        this.showCalendar = false
      } else if (this.typePicker === 'once') {
        this.dateTime = parseTime(value, this.dateFormatter)
        this.showTimer = false
      }
      this.emit()
    },
    clearTimer() {
      if (this.isInterval) {
        this.startTime = ''
        this.endTime = ''
        this.showCalendar = false
      } else {
        this.dateTime = ''
        this.showTimer = false
      }
      this.emit()
    },
    setTimer(time) {
      const timeArr = time.replace(' ', '-').split('-')
      return timeArr.map((v, vi) => {
        if (vi === 1) {
          v = parseInt(v) - 1
        } else {
          v = parseInt(v)
        }
        return v
      })
    },
    emit() {
      if (this.typePicker === 'interval') {
        this.$emit('update:start', this.startTime)
        this.$emit('update:end', this.endTime)
      } else {
        this.$emit('update:dateValue', this.dateTime)
      }
      this.$emit('change')
    }
  }
}
</script>

<style lang="scss">
.customTimer {
  margin-bottom: 30px;
  .timer-title {
    font-size: 28px;
    font-weight: bold;
    margin-bottom: 30px;
  }
  .timer-box {
    width: 100%;
    height: auto;
    display: flex;
    align-items: center;
    border-radius: 7px;
    overflow: hidden;
    &.smallFont{
      .van-field{
        padding: 0 10px;
        .van-field__control{
          font-size: 12px;
        }
      }
    }
    span {
      flex-shrink: 0;
      padding: 0 10px;
    }
    .van-cell {
      padding: 0 16px;
      &:active {
        background-color: rgba(0, 0, 0, 0);
      }
      .van-field__control {
        height: 25px;
        font-size: 14px;
        &:disabled{
          color: #323233;
          -webkit-text-fill-color: #323233;
        }
      }
      &::after{
        display: none;
      }
    }
    .down{
      font-size: 30px;
      color: #838282;;
    }
    &.isBorder{
      border: 1px solid #e9e9e9;
    }
  }
  // &.isBorder{
  //   border-bottom: 1px solid rgba(233, 233, 233, 1);
  //   padding-bottom: 25px;
  // }
}
</style>
